import { useState } from 'react';
import type { Message, TextMessage, FileMessage } from '../../types';
import { Avatar, JsonViewer } from '../UI';
import { formatTime, copyToClipboard } from '../../utils';
import { FileMessageComponent } from './FileMessage';

interface MessageItemProps {
  message: Message;
  isOwn: boolean;
  showAvatar?: boolean;
  onDelete?: (messageId: string) => void;
}

export function MessageItem({ message, isOwn, showAvatar = true, onDelete }: MessageItemProps) {
  const [copied, setCopied] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  
  const handleCopy = async () => {
    if (message.type === 'text') {
      const textMessage = message as TextMessage;
      const success = await copyToClipboard(textMessage.message);
      if (success) {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      }
    }
  };

  const handleDelete = () => {
    if (onDelete) {
      onDelete(message.id);
      setShowDeleteConfirm(false);
    }
  };

  const renderTextWithLinks = (text: string) => {
    const parts: Array<string | { href: string; label: string }> = [];
    const urlRegex = /((https?:\/\/[^\s]+)|(www\.[^\s]+\.[^\s]+))/g;
    let lastIndex = 0;
    let match;
    while ((match = urlRegex.exec(text)) !== null) {
      if (match.index > lastIndex) {
        parts.push(text.slice(lastIndex, match.index));
      }
      const raw = match[0];
      const href = raw.startsWith('http') ? raw : `http://${raw}`;
      parts.push({ href, label: raw });
      lastIndex = match.index + raw.length;
    }
    if (lastIndex < text.length) {
      parts.push(text.slice(lastIndex));
    }
    return (
      <p className="text-xs whitespace-pre-wrap text-gray-900">
        {parts.map((p, i) =>
          typeof p === 'string' ? (
            <span key={i}>{p}</span>
          ) : (
            <a
              key={i}
              href={p.href}
              target="_blank"
              rel="noopener noreferrer"
              className="text-blue-600 underline hover:text-blue-800 break-words"
            >
              {p.label}
            </a>
          )
        )}
      </p>
    );
  };
  
  const renderMessageContent = () => {
    switch (message.type) {
      case 'text': {
        const textMessage = message as TextMessage;
        const isJson = (() => {
          try {
            const v = JSON.parse(textMessage.message);
            return v && typeof v === 'object';
          } catch { return false; }
        })();
        
        return (
          <div className="group flex items-start gap-1">
            {/* 自己的消息：按钮在左边 */}
            {isOwn && (
              <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity mt-1">
                {/* 删除按钮 */}
                {onDelete && (
                  <button
                    onClick={() => setShowDeleteConfirm(true)}
                    className="inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-100 hover:bg-red-50 border border-gray-200 hover:border-red-200 transition-all duration-200"
                    title="删除消息"
                  >
                    <svg className="w-3 h-3 text-gray-500 hover:text-red-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                )}
                {/* 仅普通文本显示复制图标；JSON 由节点复制 */}
                {!isJson && (
                  <button
                    onClick={async () => { await handleCopy(); }}
                    className="inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-100 hover:bg-blue-50 border border-gray-200 hover:border-blue-200 transition-all duration-200"
                    title="复制消息"
                  >
                    {copied ? (
                      <svg className="w-3 h-3 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                    ) : (
                      <svg className="w-3 h-3 text-gray-500 hover:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                      </svg>
                    )}
                  </button>
                )}
              </div>
            )}
            
            <div
              className={`inline-block px-4 py-2 rounded-2xl max-w-sm lg:max-w-2xl xl:max-w-4xl break-words ${
                isOwn
                  ? 'bg-gray-100 text-gray-900 rounded-br-md'
                  : 'bg-gray-100 text-gray-900 rounded-bl-md'
              }`}
            >
              {isJson ? (
                <JsonViewer content={textMessage.message} isOwn={isOwn} />
              ) : (
                renderTextWithLinks(textMessage.message)
              )}
            </div>
            
            {/* 其他人的消息：按钮在右边 */}
            {!isOwn && (
              <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity mt-1">
                {/* 删除按钮 */}
                {onDelete && (
                  <button
                    onClick={() => setShowDeleteConfirm(true)}
                    className="inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-100 hover:bg-red-50 border border-gray-200 hover:border-red-200 transition-all duration-200"
                    title="删除消息"
                  >
                    <svg className="w-3 h-3 text-gray-500 hover:text-red-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                    </svg>
                  </button>
                )}
                {/* 仅普通文本显示复制图标；JSON 由节点复制 */}
                {!isJson && (
                  <button
                    onClick={async () => { await handleCopy(); }}
                    className="inline-flex items-center justify-center w-5 h-5 rounded-md bg-gray-100 hover:bg-blue-50 border border-gray-200 hover:border-blue-200 transition-all duration-200"
                    title="复制消息"
                  >
                    {copied ? (
                      <svg className="w-3 h-3 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                    ) : (
                      <svg className="w-3 h-3 text-gray-500 hover:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                      </svg>
                    )}
                  </button>
                )}
              </div>
            )}
          </div>
        );
      }
        
      case 'file': {
        const fileMessage = message as FileMessage;
        return (
          <FileMessageComponent
            message={fileMessage}
            isOwn={isOwn}
            onDelete={onDelete}
            onCopy={async (content: string) => {
              const success = await copyToClipboard(content);
              if (success) {
                setCopied(true);
                setTimeout(() => setCopied(false), 2000);
              }
            }}
          />
        );
      }
        
      default:
        return null;
    }
  };
  
  return (
    <div className={`flex items-end space-x-2 ${showAvatar ? 'mb-4' : 'mb-1'} ${isOwn ? 'flex-row-reverse space-x-reverse' : ''}`}>
      {/* 头像 */}
      {(showAvatar) ? (
        <Avatar
          name={message.username}
          color={message.randomColor}
          size="sm"
          className="flex-shrink-0 self-start"
        />
      ):(
        <div className="w-8 h-8 flex-shrink-0" />
      )}
      
      <div className={`flex flex-col ${isOwn ? 'items-end' : 'items-start'} max-w-[85%]`}>
        {/* 用户名和时间 */}
        {showAvatar && (
          <div className={`flex items-center space-x-2 mb-1 ${isOwn ? 'flex-row-reverse space-x-reverse' : ''}`}>
            <span className="text-xs font-medium text-gray-600">
              {isOwn ? '我' : message.username}
            </span>
            <span className="text-xs text-gray-400">
              {formatTime(message.timestamp.getTime())}
            </span>
          </div>
        )}
        
        {/* 消息内容 */}
        {renderMessageContent()}
      </div>
      
      {/* 删除确认对话框 */}
      {showDeleteConfirm && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-4 max-w-xs mx-4">
            <h3 className="text-sm font-medium text-gray-900 mb-2">确认删除</h3>
            <p className="text-xs text-gray-600 mb-3">确定要删除这条消息吗？此操作无法撤销。</p>
            <div className="flex gap-2 justify-end">
              <button
                onClick={() => setShowDeleteConfirm(false)}
                className="px-3 py-1.5 text-xs text-gray-600 border border-gray-300 rounded hover:bg-gray-50 transition-colors"
              >
                取消
              </button>
              <button
                onClick={handleDelete}
                className="px-3 py-1.5 text-xs bg-red-500 text-white rounded hover:bg-red-600 transition-colors"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}